package cn.buk.api.shdl.util;

import org.apache.commons.codec.binary.Base64;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;

public class ZipUtil {

  public static String gunzip(String compressedStr) {
    if (compressedStr == null) {
      return null;
    }

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ByteArrayInputStream in = null;
    GZIPInputStream ginzip = null;
    byte[] compressed = null;
    String decompressed = null;
    try {
//      String base64Code = request.getParameter("base64Code");
//      Base64 base64 = new Base64();
//      byte[] bytes = base64.decodeBase64(new String(base64Code).getBytes());


//      compressed = new sun.misc.BASE64Decoder().decodeBuffer(compressedStr);
      compressed = Base64.decodeBase64(compressedStr);
      in = new ByteArrayInputStream(compressed);
      ginzip = new GZIPInputStream(in);

      byte[] buffer = new byte[1024];
      int offset = -1;
      while ((offset = ginzip.read(buffer)) != -1) {
        out.write(buffer, 0, offset);
      }
      decompressed = out.toString();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (ginzip != null) {
        try {
          ginzip.close();
        } catch (IOException e) {
        }
      }
      if (in != null) {
        try {
          in.close();
        } catch (IOException e) {
        }
      }
      if (out != null) {
        try {
          out.close();
        } catch (IOException e) {
        }
      }
    }

    return decompressed;
  }
}
